{% extends 'base.html' %}

{% block title %}编辑球台 - {{ table.name }} - 乒乓球培训管理系统{% endblock %}

{% block page_title %}编辑球台{% endblock %}

{% block extra_css %}
<style>
    :root {
        --primary-color: #667eea;
        --primary-light: #f0f2ff;
        --secondary-color: #764ba2;
        --success-color: #10b981;
        --warning-color: #f59e0b;
        --danger-color: #ef4444;
        --gray-50: #f9fafb;
        --gray-100: #f3f4f6;
        --gray-200: #e5e7eb;
        --gray-300: #d1d5db;
        --gray-400: #9ca3af;
        --gray-500: #6b7280;
        --gray-600: #4b5563;
        --gray-700: #374151;
        --gray-800: #1f2937;
        --gray-900: #111827;
        --border-radius: 12px;
        --border-radius-lg: 16px;
        --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
        --shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
        --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
        --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
        --shadow-xl: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
    }

    .page-container {
        min-height: calc(100vh - 120px);
        background: linear-gradient(135deg, var(--primary-light) 0%, var(--gray-50) 100%);
        padding: 2rem 0;
    }

    .edit-container {
        max-width: 900px;
        margin: 0 auto;
        padding: 0 1rem;
    }

    .header-card {
        background: white;
        border-radius: var(--border-radius-lg);
        padding: 2rem;
        margin-bottom: 2rem;
        box-shadow: var(--shadow-lg);
        border: 1px solid var(--gray-200);
    }

    .header-content {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 2rem;
    }

    .header-text {
        flex: 1;
    }

    .page-title {
        font-size: 2rem;
        font-weight: 700;
        color: var(--gray-900);
        margin: 0 0 0.5rem 0;
        background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    .page-subtitle {
        color: var(--gray-600);
        font-size: 1rem;
        margin: 0;
        line-height: 1.6;
    }

    .table-status-card {
        background: var(--gray-50);
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius);
        padding: 1.5rem;
        min-width: 200px;
    }

    .table-id {
        font-size: 0.875rem;
        color: var(--gray-500);
        margin: 0 0 0.75rem 0;
        font-weight: 500;
    }

    .status-badge {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.5rem 1rem;
        border-radius: 9999px;
        font-size: 0.875rem;
        font-weight: 600;
        border: 1px solid transparent;
    }

    .status-available {
        background: rgb(16, 185, 129, 0.1);
        color: var(--success-color);
        border-color: rgb(16, 185, 129, 0.2);
    }

    .status-maintenance {
        background: rgb(245, 158, 11, 0.1);
        color: var(--warning-color);
        border-color: rgb(245, 158, 11, 0.2);
    }

    .status-disabled {
        background: rgb(239, 68, 68, 0.1);
        color: var(--danger-color);
        border-color: rgb(239, 68, 68, 0.2);
    }

    .form-card {
        background: white;
        border-radius: var(--border-radius-lg);
        box-shadow: var(--shadow-lg);
        border: 1px solid var(--gray-200);
        overflow: hidden;
    }

    .alert-info {
        background: linear-gradient(135deg, #fef3c7, #fde68a);
        border: 1px solid #f59e0b;
        border-radius: var(--border-radius);
        padding: 1.5rem;
        margin-bottom: 2rem;
        display: flex;
        align-items: flex-start;
        gap: 1rem;
    }

    .alert-icon {
        color: var(--warning-color);
        font-size: 1.25rem;
        margin-top: 0.125rem;
        flex-shrink: 0;
    }

    .alert-content {
        flex: 1;
    }

    .alert-title {
        font-weight: 600;
        color: #92400e;
        margin: 0 0 0.5rem 0;
        font-size: 1rem;
    }

    .alert-text {
        color: #92400e;
        font-size: 0.875rem;
        margin: 0;
        line-height: 1.5;
    }

    .form-content {
        padding: 2rem;
    }

    .section {
        margin-bottom: 2.5rem;
    }

    .section:last-child {
        margin-bottom: 0;
    }

    .section-header {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        margin-bottom: 1.5rem;
        padding-bottom: 0.75rem;
        border-bottom: 2px solid var(--gray-100);
    }

    .section-icon {
        width: 2rem;
        height: 2rem;
        background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 1rem;
    }

    .section-title {
        font-size: 1.25rem;
        font-weight: 600;
        color: var(--gray-900);
        margin: 0;
    }

    .field-group {
        margin-bottom: 2rem;
    }

    .field-group:last-child {
        margin-bottom: 0;
    }

    .field-label {
        display: block;
        font-weight: 600;
        color: var(--gray-700);
        margin-bottom: 0.75rem;
        font-size: 0.95rem;
    }

    .field-label .required {
        color: var(--danger-color);
        margin-left: 0.25rem;
    }

    .form-control, .form-select {
        width: 100%;
        padding: 0.875rem 1rem;
        border: 2px solid var(--gray-200);
        border-radius: var(--border-radius);
        font-size: 1rem;
        transition: all 0.2s ease;
        background: white;
    }

    .form-control:focus, .form-select:focus {
        outline: none;
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgb(102, 126, 234, 0.1);
    }

    .form-control.is-invalid, .form-select.is-invalid {
        border-color: var(--danger-color);
        box-shadow: 0 0 0 3px rgb(239, 68, 68, 0.1);
    }

    .form-control.is-valid, .form-select.is-valid {
        border-color: var(--success-color);
        box-shadow: 0 0 0 3px rgb(16, 185, 129, 0.1);
    }

    .field-help {
        margin-top: 0.5rem;
        font-size: 0.875rem;
        color: var(--gray-500);
        line-height: 1.4;
    }

    .field-error {
        margin-top: 0.5rem;
        font-size: 0.875rem;
        color: var(--danger-color);
        font-weight: 500;
    }

    .status-selector {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 1rem;
        margin-top: 1rem;
    }

    .status-option {
        position: relative;
        background: var(--gray-50);
        border: 2px solid var(--gray-200);
        border-radius: var(--border-radius);
        padding: 1.5rem 1rem;
        cursor: pointer;
        transition: all 0.2s ease;
        text-align: center;
    }

    .status-option:hover {
        border-color: var(--primary-color);
        background: var(--primary-light);
        transform: translateY(-2px);
        box-shadow: var(--shadow-md);
    }

    .status-option.selected {
        border-color: var(--primary-color);
        background: var(--primary-light);
        box-shadow: var(--shadow-md);
    }

    .status-option input[type="radio"] {
        position: absolute;
        opacity: 0;
        pointer-events: none;
    }

    .status-option-icon {
        font-size: 2rem;
        margin-bottom: 0.75rem;
        display: block;
    }

    .status-option-label {
        font-weight: 600;
        color: var(--gray-900);
        margin-bottom: 0.5rem;
        font-size: 1rem;
    }

    .status-option-desc {
        font-size: 0.875rem;
        color: var(--gray-600);
        line-height: 1.3;
    }

    .checkbox-field {
        background: var(--gray-50);
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius);
        padding: 1.5rem;
        margin-top: 1rem;
    }

    .checkbox-wrapper {
        display: flex;
        align-items: flex-start;
        gap: 1rem;
    }

    .checkbox-input {
        width: 1.25rem;
        height: 1.25rem;
        accent-color: var(--primary-color);
        margin: 0;
        flex-shrink: 0;
    }

    .checkbox-content {
        flex: 1;
    }

    .checkbox-label {
        font-weight: 600;
        color: var(--gray-900);
        margin: 0 0 0.5rem 0;
        font-size: 1rem;
    }

    .checkbox-description {
        font-size: 0.875rem;
        color: var(--gray-600);
        line-height: 1.4;
        margin: 0;
    }

    .actions-bar {
        background: var(--gray-50);
        border-top: 1px solid var(--gray-200);
        padding: 2rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 1rem;
    }

    .actions-left {
        display: flex;
        gap: 1rem;
    }

    .btn {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.875rem 1.5rem;
        border-radius: var(--border-radius);
        font-weight: 600;
        font-size: 0.95rem;
        text-decoration: none;
        border: 2px solid transparent;
        transition: all 0.2s ease;
        cursor: pointer;
        line-height: 1;
    }

    .btn-primary {
        background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
        color: white;
        box-shadow: var(--shadow);
    }

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-lg);
        color: white;
        text-decoration: none;
    }

    .btn-secondary {
        background: var(--gray-100);
        color: var(--gray-700);
        border-color: var(--gray-300);
    }

    .btn-secondary:hover {
        background: var(--gray-200);
        color: var(--gray-800);
        text-decoration: none;
        transform: translateY(-1px);
    }

    .btn-outline {
        background: white;
        color: var(--gray-700);
        border-color: var(--gray-300);
    }

    .btn-outline:hover {
        background: var(--gray-50);
        color: var(--gray-800);
        text-decoration: none;
    }

    .btn-warning {
        background: var(--warning-color);
        color: white;
    }

    .btn-warning:hover {
        background: #d97706;
        color: white;
        text-decoration: none;
    }

    .btn:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none !important;
    }

    .change-indicator {
        background: linear-gradient(135deg, #fef3c7, #fde68a);
        border: 1px solid var(--warning-color);
        border-radius: var(--border-radius);
        padding: 1rem;
        margin-top: 0.75rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .change-indicator-icon {
        color: var(--warning-color);
        font-size: 1.1rem;
        flex-shrink: 0;
    }

    .change-indicator-text {
        color: #92400e;
        font-size: 0.875rem;
        margin: 0;
        font-weight: 500;
    }

    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }

    .loading-content {
        background: white;
        border-radius: var(--border-radius-lg);
        padding: 2rem;
        text-align: center;
        box-shadow: var(--shadow-xl);
    }

    .loading-spinner {
        width: 3rem;
        height: 3rem;
        border: 3px solid var(--gray-200);
        border-top: 3px solid var(--primary-color);
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 1rem auto;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .loading-text {
        color: var(--gray-700);
        font-weight: 500;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
        .page-container {
            padding: 1rem 0;
        }

        .edit-container {
            padding: 0 0.5rem;
        }

        .header-card {
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .header-content {
            flex-direction: column;
            gap: 1.5rem;
        }

        .table-status-card {
            width: 100%;
            min-width: auto;
        }

        .page-title {
            font-size: 1.75rem;
        }

        .form-content {
            padding: 1.5rem;
        }

        .status-selector {
            grid-template-columns: 1fr;
        }

        .actions-bar {
            flex-direction: column;
            align-items: stretch;
            gap: 1rem;
        }

        .actions-left {
            justify-content: center;
        }

        .btn {
            width: 100%;
            justify-content: center;
        }

        .checkbox-wrapper {
            flex-direction: column;
            gap: 0.75rem;
        }
    }

    @media (max-width: 480px) {
        .header-card {
            padding: 1rem;
        }

        .form-content {
            padding: 1rem;
        }

        .actions-bar {
            padding: 1.5rem;
        }

        .page-title {
            font-size: 1.5rem;
        }

        .section-title {
            font-size: 1.125rem;
        }
    }

    /* 动画 */
    .form-card {
        animation: slideUp 0.3s ease-out;
    }

    @keyframes slideUp {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .status-option {
        animation: fadeIn 0.2s ease-out;
    }

    .status-option:nth-child(1) { animation-delay: 0.1s; }
    .status-option:nth-child(2) { animation-delay: 0.2s; }
    .status-option:nth-child(3) { animation-delay: 0.3s; }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="page-container">
    <div class="edit-container">
        <!-- 页面头部 -->
        <div class="header-card">
            <div class="header-content">
                <div class="header-text">
                    <h1 class="page-title">编辑球台 - {{ table.name }}</h1>
                    <p class="page-subtitle">修改球台的基本信息和状态设置，确保预约系统的正常运行</p>
                </div>
                <div class="table-status-card">
                    <p class="table-id">球台编号 #{{ table.id }}</p>
                    <div class="status-badge status-{{ table.status }}">
                        {% if table.status == 'available' %}
                            <i class="bi bi-check-circle-fill"></i>
                            可用状态
                        {% elif table.status == 'maintenance' %}
                            <i class="bi bi-tools"></i>
                            维护中
                        {% elif table.status == 'disabled' %}
                            <i class="bi bi-x-circle-fill"></i>
                            已禁用
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>

        <!-- 重要提醒 -->
        <div class="alert-info">
            <i class="bi bi-exclamation-triangle-fill alert-icon"></i>
            <div class="alert-content">
                <h6 class="alert-title">编辑提醒</h6>
                <p class="alert-text">
                    修改球台信息可能会影响现有的预约记录。如果球台正在使用中，建议在空闲时间进行操作。
                    状态变更将立即生效并影响用户的预约选择。
                </p>
            </div>
        </div>

        <!-- 编辑表单 -->
        <div class="form-card">
            <form method="POST" enctype="multipart/form-data" novalidate>
                {{ form.hidden_tag() }}

                <div class="form-content">
                    <!-- 基本信息 -->
                    <div class="section">
                        <div class="section-header">
                            <div class="section-icon">
                                <i class="bi bi-info-circle"></i>
                            </div>
                            <h2 class="section-title">基本信息</h2>
                        </div>

                        <div class="field-group">
                            <label class="field-label">
                                球台名称
                                <span class="required">*</span>
                            </label>
                            {{ form.name(class="form-control" + (" is-invalid" if form.name.errors else ""),
                                         placeholder="请输入易于识别的球台名称，如：1号台、VIP包间等") }}
                            {% if form.name.errors %}
                                {% for error in form.name.errors %}
                                <div class="field-error">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="field-help">
                                球台名称将在预约系统中向学员展示，建议使用简洁明了的命名方式
                            </div>
                        </div>

                        <div class="field-group">
                            <label class="field-label">
                                所属校区
                                <span class="required">*</span>
                            </label>
                            {{ form.campus_id(class="form-select" + (" is-invalid" if form.campus_id.errors else "")) }}
                            {% if form.campus_id.errors %}
                                {% for error in form.campus_id.errors %}
                                <div class="field-error">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="field-help">
                                当前归属：{{ table.campus.name if table.campus else '未分配校区' }}
                                {% if current_user.is_campus_admin() %}
                                <div class="change-indicator">
                                    <i class="bi bi-info-circle change-indicator-icon"></i>
                                    <p class="change-indicator-text">作为校区管理员，您只能将球台分配到自己管理的校区</p>
                                </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>

                    <!-- 状态设置 -->
                    <div class="section">
                        <div class="section-header">
                            <div class="section-icon">
                                <i class="bi bi-toggle-on"></i>
                            </div>
                            <h2 class="section-title">状态设置</h2>
                        </div>

                        <div class="field-group">
                            <label class="field-label">
                                球台状态
                                <span class="required">*</span>
                            </label>
                            <div class="status-selector">
                                {% for value, label in form.status.choices %}
                                <label class="status-option {% if form.status.data == value %}selected{% endif %}">
                                    <input type="radio" name="status" value="{{ value }}" {% if form.status.data == value %}checked{% endif %}>
                                    {% if value == 'available' %}
                                        <i class="bi bi-check-circle-fill status-option-icon" style="color: var(--success-color);"></i>
                                        <div class="status-option-label">可用状态</div>
                                        <div class="status-option-desc">球台正常开放，可接受预约</div>
                                    {% elif value == 'maintenance' %}
                                        <i class="bi bi-tools status-option-icon" style="color: var(--warning-color);"></i>
                                        <div class="status-option-label">维护中</div>
                                        <div class="status-option-desc">暂时停用，正在维护保养</div>
                                    {% elif value == 'disabled' %}
                                        <i class="bi bi-x-circle-fill status-option-icon" style="color: var(--danger-color);"></i>
                                        <div class="status-option-label">禁用状态</div>
                                        <div class="status-option-desc">完全停用，不可预约使用</div>
                                    {% endif %}
                                </label>
                                {% endfor %}
                            </div>
                            {% if form.status.errors %}
                                {% for error in form.status.errors %}
                                <div class="field-error">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="field-help">
                                状态变更将立即生效。维护中和禁用状态的球台不会出现在预约选项中。
                            </div>
                        </div>

                        <div class="field-group">
                            <div class="checkbox-field">
                                <div class="checkbox-wrapper">
                                    {{ form.is_active(class="checkbox-input") }}
                                    <div class="checkbox-content">
                                        <label for="{{ form.is_active.id }}" class="checkbox-label">
                                            {{ form.is_active.label.text }}
                                        </label>
                                        <p class="checkbox-description">
                                            启用后，球台将根据状态设置对用户可见。禁用时球台将被隐藏，但不影响已有预约。
                                            当前状态：
                                            <span style="color: {% if table.is_active %}var(--success-color){% else %}var(--danger-color){% endif %}; font-weight: 600;">
                                                {% if table.is_active %}已启用{% else %}已禁用{% endif %}
                                            </span>
                                        </p>
                                    </div>
                                </div>
                            </div>
                            {% if form.is_active.errors %}
                                {% for error in form.is_active.errors %}
                                <div class="field-error">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                        </div>
                    </div>
                </div>

                <!-- 操作按钮区域 -->
                <div class="actions-bar">
                    <div class="actions-left">
                        <a href="{{ url_for('tables.detail', id=table.id) }}" class="btn btn-secondary">
                            <i class="bi bi-arrow-left"></i>
                            返回详情
                        </a>
                        <a href="{{ url_for('tables.list') }}" class="btn btn-outline">
                            <i class="bi bi-list"></i>
                            球台列表
                        </a>
                    </div>
                    <button type="submit" class="btn btn-primary" id="submitBtn">
                        <i class="bi bi-check-circle"></i>
                        保存修改
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 加载遮罩 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-content">
        <div class="loading-spinner"></div>
        <div class="loading-text">正在保存修改...</div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.querySelector('form');
    const submitBtn = document.getElementById('submitBtn');
    const loadingOverlay = document.getElementById('loadingOverlay');

    // 记录表单初始值
    const originalValues = {
        name: document.querySelector('input[name="name"]').value,
        campus_id: document.querySelector('select[name="campus_id"]').value,
        status: document.querySelector('input[name="status"]:checked')?.value,
        is_active: document.querySelector('input[name="is_active"]').checked
    };

    // 检查表单变更
    function checkFormChanges() {
        const currentValues = {
            name: document.querySelector('input[name="name"]').value,
            campus_id: document.querySelector('select[name="campus_id"]').value,
            status: document.querySelector('input[name="status"]:checked')?.value,
            is_active: document.querySelector('input[name="is_active"]').checked
        };

        let hasChanges = false;
        for (let key in originalValues) {
            if (originalValues[key] !== currentValues[key]) {
                hasChanges = true;
                break;
            }
        }

        // 更新按钮状态
        if (hasChanges) {
            submitBtn.classList.remove('btn-primary');
            submitBtn.classList.add('btn-warning');
            submitBtn.innerHTML = '<i class="bi bi-exclamation-circle"></i>保存修改';
        } else {
            submitBtn.classList.remove('btn-warning');
            submitBtn.classList.add('btn-primary');
            submitBtn.innerHTML = '<i class="bi bi-check-circle"></i>保存修改';
        }

        return hasChanges;
    }

    // 状态选项点击处理
    const statusOptions = document.querySelectorAll('.status-option');
    statusOptions.forEach(option => {
        option.addEventListener('click', function() {
            const radio = this.querySelector('input[type="radio"]');
            if (radio && !radio.checked) {
                radio.checked = true;

                // 更新视觉状态
                statusOptions.forEach(opt => opt.classList.remove('selected'));
                this.classList.add('selected');

                checkFormChanges();
            }
        });
    });

    // 实时验证
    function validateField(field) {
        if (field.checkValidity()) {
            field.classList.remove('is-invalid');
            field.classList.add('is-valid');
        } else {
            field.classList.remove('is-valid');
            field.classList.add('is-invalid');
        }
    }

    // 为表单元素添加监听
    const formElements = form.querySelectorAll('input, select, textarea');
    formElements.forEach(element => {
        element.addEventListener('input', checkFormChanges);
        element.addEventListener('change', checkFormChanges);

        if (element.hasAttribute('required')) {
            element.addEventListener('blur', () => validateField(element));
            element.addEventListener('input', () => {
                if (element.classList.contains('is-invalid')) {
                    validateField(element);
                }
            });
        }
    });

    // 表单提交处理
    form.addEventListener('submit', function(e) {
        const hasChanges = checkFormChanges();

        if (!hasChanges) {
            e.preventDefault();
            alert('检测到没有任何修改，无需保存。');
            return false;
        }

        // 基础验证
        const nameField = document.querySelector('input[name="name"]');
        const campusField = document.querySelector('select[name="campus_id"]');

        if (!nameField.value.trim()) {
            e.preventDefault();
            nameField.focus();
            nameField.classList.add('is-invalid');
            return false;
        }

        if (!campusField.value) {
            e.preventDefault();
            campusField.focus();
            campusField.classList.add('is-invalid');
            return false;
        }

        // 确认提交
        if (!confirm('确认保存这些修改吗？\n\n注意：状态变更可能会影响用户的预约体验。')) {
            e.preventDefault();
            return false;
        }

        // 显示加载状态
        submitBtn.disabled = true;
        loadingOverlay.style.display = 'flex';

        // 5秒超时保护
        setTimeout(() => {
            if (submitBtn.disabled) {
                submitBtn.disabled = false;
                loadingOverlay.style.display = 'none';
                alert('保存超时，请检查网络连接后重试。');
            }
        }, 5000);
    });

    // 页面离开前检查
    window.addEventListener('beforeunload', function(e) {
        if (checkFormChanges()) {
            e.preventDefault();
            e.returnValue = '您有未保存的修改，确定要离开吗？';
        }
    });

    // 键盘快捷键
    document.addEventListener('keydown', function(e) {
        // Ctrl+S 保存
        if (e.ctrlKey && e.key === 's') {
            e.preventDefault();
            if (checkFormChanges()) {
                form.requestSubmit();
            }
        }

        // Esc 取消
        if (e.key === 'Escape') {
            const confirmLeave = checkFormChanges() ?
                confirm('您有未保存的修改，确定要离开吗？') : true;

            if (confirmLeave) {
                window.location.href = "{{ url_for('tables.detail', id=table.id) }}";
            }
        }
    });

    // 初始化
    checkFormChanges();

    // 自动聚焦到名称字段
    setTimeout(() => {
        const nameField = document.querySelector('input[name="name"]');
        if (nameField) {
            nameField.focus();
            nameField.select();
        }
    }, 100);
});
</script>
{% endblock %}